<template>
  <el-main>
    <sys-dialog
      :title="sysDialog.title"
      :width="sysDialog.width"
      :height="sysDialog.height"
      :visible="sysDialog.visible"
      @onClose="sysDialogClose"
      @onConfirm="sysDialogConfirm"
    >
      <div slot="content">
        <el-form
          ref="entityForm"
          :model="entityModel"
          :rules="entityRules"
          :inline="true"
          label-width="80px"
        >
          <el-row>
            <el-form-item prop="name" label="角色名称">
              <el-input v-model="entityModel.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item prop="orderNum" label="显示顺序">
              <el-input-number v-model="entityModel.orderNum" :min="1" />
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </sys-dialog>
    <el-form
      ref="searchForm"
      :model="searchModel"
      :rules="searchRules"
      :inline="true"
      label-width="80px"
    >
      <el-form-item v-if="checkPermission(['sys:role:search'])" prop="name">
        <el-input v-model="searchModel.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button v-if="checkPermission(['sys:role:search'])" icon="el-icon-search" @click="searchHandler()">查询</el-button>
        <el-button v-if="checkPermission(['sys:role:search'])" icon="el-icon-delete" @click="resethHandler()">重置</el-button>
        <el-button v-if="checkPermission(['sys:role:add'])" type="primary" icon="el-icon-plus" @click="addHandler()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableList"
      style="width: 100%;margin-bottom: 18px;"
      row-key="id"
      border
      stripe
      highlight-current-row
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="orderNum" label="显示顺序" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="360">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['sys:role:update'])" :disabled="scope.row.name === '超级管理员'" type="primary" icon="el-icon-edit-outline" @click="updateHandler(scope.row)">编辑</el-button>
          <el-button v-if="checkPermission(['sys:role:delete'])" :disabled="scope.row.name === '超级管理员'" type="danger" icon="el-icon-close" @click="deleteHandler(scope.row)">删除</el-button>
          <el-button v-if="checkPermission(['sys:role:assign'])" type="success" icon="el-icon-share" @click="assignHandler(scope.row)">分配菜单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="tableTotal>0"
      :total="tableTotal"
      :page.sync="searchModel.pageNum"
      :limit.sync="searchModel.pageSize"
      @pagination="fetchList"
    />
    <sys-dialog
      :title="sysMenuDialog.title"
      :width="sysMenuDialog.width"
      :height="sysMenuDialog.height"
      :visible="sysMenuDialog.visible"
      @onClose="sysMenuDialogClose"
      @onConfirm="sysMenuDialogConfirm"
    >
      <div slot="content-header">
        <el-input v-model="permissionTreeFilterText" placeholder="请输入菜单名进行过滤" class="permissionTreeFilterClass" />
      </div>
      <div slot="content">
        <el-tree
          ref="permissionTree"
          show-checkbox
          highlight-current
          default-expand-all
          :data="permissionTreeData"
          :props="permissionTreeProps"
          :filter-node-method="permissionTreeFilterNode"
          node-key="id"
        />
      </div>
    </sys-dialog>
  </el-main>
</template>

<script>
import checkPermission from '@/utils/permission'
import { add, deleteById, update, getById, getPage, getPermission, assignMenu } from '@/api/sysRole'
import Pagination from '@/components/Pagination'
import SysDialog from '@/components/SysDialog'
export default {
  name: 'SysRole',
  components: {
    Pagination,
    SysDialog
  },
  props: {},
  data() {
    return {
      loading: false,
      tableList: [],
      tableTotal: 0,
      sysDialog: {
        title: '系统提示',
        type: 'add',
        visible: false,
        width: 590,
        height: 75
      },
      entityModel: {
        id: null,
        name: null,
        orderNum: null,
        createTime: null
      },
      entityRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入角色名称' }]
      },
      searchModel: {
        name: null,
        pageNum: 1,
        pageSize: 10
      },
      searchRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入角色名称' }]
      },
      sysMenuDialog: {
        title: '系统提示',
        type: 'assign',
        visible: false,
        width: 400,
        height: 390
      },
      permissionTreeData: [],
      permissionTreeProps: {
        label: 'name',
        children: 'children'
      },
      permissionTreeFilterText: '',
      roleCheckedId: null
    }
  },
  watch: {
    permissionTreeFilterText(val) {
      this.$refs.permissionTree.filter(val)
    }
  },
  created() {
    this.fetchList()
  },
  mounted() {},
  methods: {
    checkPermission,
    fetchList(data) {
      this.loading = true
      // 分页信息改变
      if (data !== undefined) {
        this.searchModel.pageNum = data.page
        this.searchModel.pageSize = data.limit
      }
      // 分页获取列表
      getPage(this.searchModel).then(response => {
        if (response.code === 200) {
          this.tableList = response.data.list
          this.tableTotal = response.data.total
          this.searchModel.pageNum = response.data.pageNum
          this.searchModel.pageSize = response.data.pageSize
          this.loading = false
        }
      })
    },
    sysDialogOpen(title, type) {
      // 设置窗口属性
      this.sysDialog.title = title
      this.sysDialog.type = type
      this.sysDialog.visible = true
      // 重置表单内容
      this.$nextTick(() => {
        this.$refs.entityForm.resetFields()
        this.entityModel.id = null
      })
    },
    sysDialogClose() {
      this.sysDialog.visible = false
    },
    sysDialogConfirm() {
      this.$refs.entityForm.validate(valid => {
        if (valid) {
          if (this.sysDialog.type === 'add') {
            add(this.entityModel).then(response => {
              if (response.code === 200) {
                this.$notify.success({ title: '系统提示', message: response.msg })
                this.fetchList()
                this.sysDialogClose()
              }
            })
          }
          if (this.sysDialog.type === 'update') {
            update(this.entityModel).then(response => {
              if (response.code === 200) {
                this.$notify.success({ title: '系统提示', message: response.msg })
                this.fetchList()
                this.sysDialogClose()
              }
            })
          }
        }
      })
    },
    searchHandler() {
      this.$refs.searchForm.validate(valid => {
        if (valid) {
          this.fetchList()
        }
      })
    },
    resethHandler() {
      this.$refs.searchForm.resetFields()
      this.searchModel.pageNum = 1
      this.fetchList()
    },
    addHandler() {
      this.sysDialogOpen('新增系统角色', 'add')
    },
    updateHandler(row) {
      this.sysDialogOpen('修改系统角色', 'update')
      getById({ id: row.id }).then(response => {
        if (response.code === 200) {
          this.entityModel = response.data
        }
      })
    },
    deleteHandler(row) {
      this.$confirm('此操作将永久删除该记录及菜单映射记录，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById({ id: row.id }).then(response => {
          if (response.code === 200) {
            this.$notify.success({ title: '系统提示', message: response.msg })
            this.fetchList()
          }
        })
      }).catch(() => {})
    },
    assignHandler(row) {
      // 保存选择结果
      this.roleCheckedId = row.id
      // 设置窗口属性
      this.sysMenuDialog.title = `为【 ${row.name} 】分配菜单`
      this.sysMenuDialog.visible = true
      // 加载权限数据
      getPermission({ 'id': row.id }).then((response) => {
        if (response.code === 200) {
          this.permissionTreeData = response.data.menus
          const checks = response.data.checks
          // 回显用户选择
          if (checks) {
            this.$nextTick(() => {
              for (let index = 0; index < checks.length; index++) {
                const check = checks[index]
                this.$refs.permissionTree.setChecked(check, true, false)
              }
            })
          }
        }
      })
    },
    sysMenuDialogClose() {
      this.sysMenuDialog.visible = false
      this.$refs.permissionTree.setCheckedKeys([])
      this.permissionTreeFilterText = ''
    },
    sysMenuDialogConfirm() {
      // 获取选择菜单
      const mids = this.$refs.permissionTree.getCheckedKeys().concat(this.$refs.permissionTree.getHalfCheckedKeys())
      // 保存分配结果
      assignMenu({ 'rid': this.roleCheckedId, 'mids': mids }).then((response) => {
        if (response.code === 200) {
          this.$notify.success({ title: '系统提示', message: response.msg })
          this.sysMenuDialogClose()
        }
      })
    },
    permissionTreeFilterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
  }
}
</script>

<style lang="scss" scoped>
.pagination-container {
  margin: 0;
  padding: 0;
}
.permissionTreeFilterClass {
  margin-bottom: 14px;
}
</style>
